//
//  ExpertDetailViewController.m
//  DaJiang
//
//  Created by sally on 16/10/9.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "CommentCell.h"
#import "ExpertDetailBtnCell.h"
#import "ExpertDetailTextCell.h"
#import "ExpertDetailThemeCell.h"
#import "ExpertDetailTitleCell.h"
#import "ExpertDetailViewController.h"
#import "ExpertModel.h"
#import <UMSocialCore/UMSocialCore.h>
#import <UShareUI/UMSocialUIManager.h>

#define TextProtectPlan @"1.在专家接受约见后，学员才需付款。\n2.一旦确认约见，不可单方面取消\n客服电话：400-673-798\n工作时间：10:00-19:00"
#define CommentCountLimit 3

@interface ExpertDetailViewController () <ExpertDetailBtnDelegate, UIGestureRecognizerDelegate>

//headView相关
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UIImageView *headImage;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *jobLabel;
@property (weak, nonatomic) IBOutlet UILabel *locLabel;
@property (weak, nonatomic) IBOutlet UILabel *seenLabel;
@property (weak, nonatomic) IBOutlet UILabel *missLabel;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *collectBtn;
@property (weak, nonatomic) IBOutlet UIView *orderView;
@property (weak, nonatomic) IBOutlet UITableView *themeTableView; //预约话题table
@property (strong, nonatomic) NSArray *titleData;
@property (strong, nonatomic) ExpertDetailModel *expertDetail;
@property (strong, nonatomic) NSString *aboutExpert; //关于专家
@property (assign, nonatomic) NSInteger selectIndex; //选中的话题
@property (assign, nonatomic) BOOL isShowMore; //是否显示更多关于专家

@end

@implementation ExpertDetailViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  [self initControl];
  [self initData];
  [self loadData];
}

#pragma mark 初始化控件
- (void)initControl {
  self.title = self.expertName;
  UIButton *rightBtn = [[CommonMethod sharedCommonMethod] navigationItemWithImage:@"share_ic"];
  [rightBtn addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
  self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
  self.headerView.height = GExpertImageHeight;
  [self loadThemeTableView];
}

#pragma mark 初始化数据
- (void)initData {
  self.titleData = @[ @"专家话题", @"关于专家", @"评价", @"约见保障计划" ];
  self.selectIndex = -1;
}

#pragma mark 加载数据
- (void)loadData {
  //FIXME: 为什么，这里必须是window才能是最外层显示缓冲圈
  UIWindow *window = [UIApplication sharedApplication].keyWindow;
  MBProgressHUD *hud = [[CommonMethod sharedCommonMethod] createProgressHUDInView:window withMessage:@""];

  [ExpertDetailModel queryExpertDetailWithProUid:self.expertId completion:^(ExpertDetailModel *expertDetail) {
    if (expertDetail) {
      self.expertDetail = expertDetail;
      if (self.expertDetail.pro_user_info.count > 0) {
        self.title = [[self.expertDetail.pro_user_info[0] user_data]user_name];
        self.aboutExpert = [[self.expertDetail.pro_user_info[0] user_data] user_pro_desc];
      }
      [self loadHeadView];
      [self.tableView reloadData];
    } else {
      NSError *error = [ExpertDetailModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
    hud.hidden = YES;
  }];
}

#pragma mark - action
#pragma mark 点击收藏
- (IBAction)actionOnCollect:(id)sender {
  [[CommonMethod sharedCommonMethod]createProgressHUDInView:self.view withMessage:@""];
  if (self.collectBtn.isSelected) {//取消收藏操作
    [UserModel cancelCollectExpertWithProUid:self.expertId completion:^(BOOL isSucceed) {
      [self operateCollect:isSucceed];
      if (isSucceed) {
        [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"取消收藏成功"];
      }
    }];
  }else{//收藏操作
    [UserModel collectExpertWithProUid:self.expertId completion:^(BOOL isSucceed) {
      [self operateCollect:isSucceed];
      if (isSucceed) {
        [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"收藏成功"];
      }
    }];
  }
}

#pragma mark 点击预约
- (IBAction)actionOnOrder:(id)sender {
  if (self.themeTableView.isHidden) {
    self.orderView.hidden = NO;
    self.themeTableView.hidden = NO;
    [self.themeTableView reloadData];
  } else {
    if (self.expertDetail.pro_topic.count < 1) {
      [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"该专家还没发布过话题"];
      return;
    }
    if (self.selectIndex > -1) {
      OrderDetailViewController *vc = [OperationManager gotoOrderDetailVcWithType:OrderDetailType_Normal status:OrderNormalStatus_FillIn];
      vc.expertDetail = self.expertDetail;
      vc.topicModel = [self.expertDetail.pro_topic objectAtIndex:self.selectIndex];
    }
  }
}

#pragma mark - TableView data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  if (tableView == self.tableView) {
    return 4;
  } else { //预约话题列表
    return 1;
  }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  if (tableView == self.tableView) {
    if (section == 0) { //专家话题
      return self.expertDetail.pro_topic.count + 1;
    } else if (section == 1) { //关于专家<=3
      if ([self getAboutExpertTextHeight] > sevenLineHeight && !self.isShowMore) {
        return 3;
      }else{
        return 2;
      }
    } else if (section == 2) { //评论<=5
      if (self.expertDetail.pro_topic_comments.count > CommentCountLimit) {
        return CommentCountLimit + 2;
      } else {
        return self.expertDetail.pro_topic_comments.count + 1;
      }
    } else { //约见保障计划
      return 2;
    }
  } else { //预约话题列表
    return self.expertDetail.pro_topic.count;
  }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  if (tableView == self.tableView) {
    return 0.1; //section头部高度
  } else {      //预约话题列表
    return 0;
  }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
  if (tableView == self.tableView) {
    return GNormalMargin; //section底部高度
  } else {                //预约话题列表
    return 0;
  }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  if (tableView == self.tableView) {
    if (indexPath.section == 1 && indexPath.row == 1) { //关于专家
      return [ExpertDetailTextCell cellHeight];
    } else if (indexPath.section == 2 && indexPath.row != 0 && indexPath.row != CommentCountLimit + 1) { //评论
      return [CommentCell cellHeight];
    } else if (indexPath.section == 3 && indexPath.row == 1) { //约见保障计划
      return [ExpertDetailTextCell cellHeight];
    } else {
      UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
      return cell.frame.size.height;
    }
  } else { //预约话题列表
    return NavHeight;
  }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  if (tableView == self.tableView) {

    if (indexPath.row == 0) { //标题
      ExpertDetailTitleCell *cell = (ExpertDetailTitleCell *) [tableView dequeueReusableCellWithIdentifier:@"ExpertDetailTitleCell"];
      if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ExpertDetailTitleCell" owner:nil options:nil] lastObject];
      }
      cell.cellData = [self.titleData objectAtIndex:indexPath.section];
      cell.selectionStyle = UITableViewCellSelectionStyleNone;

      return cell;
    } else {

      if (indexPath.section == 0) { //专家话题
        ExpertDetailThemeCell *cell = (ExpertDetailThemeCell *) [tableView dequeueReusableCellWithIdentifier:@"ExpertDetailThemeCell"];
        if (!cell) {
          cell = [[[NSBundle mainBundle] loadNibNamed:@"ExpertDetailThemeCell" owner:nil options:nil] lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        cell.cellData = [self.expertDetail.pro_topic objectAtIndex:indexPath.row - 1];

        return cell;
      } else if (indexPath.section == 1) { //关于专家

        if (indexPath.row == 2) { //查看更多
          ExpertDetailBtnCell *cell = (ExpertDetailBtnCell *) [tableView dequeueReusableCellWithIdentifier:@"ExpertDetailBtnCell"];
          if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ExpertDetailBtnCell" owner:nil options:nil] lastObject];
          }
          cell.selectionStyle = UITableViewCellSelectionStyleNone;
          cell.btnType = ExpertDetailBtnType_Desc;
          cell.delegate = self;

          return cell;
        } else {
          ExpertDetailTextCell *cell = (ExpertDetailTextCell *) [tableView dequeueReusableCellWithIdentifier:@"ExpertDetailTextCell"];
          if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ExpertDetailTextCell" owner:nil options:nil] lastObject];
          }
          cell.selectionStyle = UITableViewCellSelectionStyleNone;
          cell.isLimitHeight = !self.isShowMore;
          //隐藏分割线（将其移至屏幕外）
          cell.separatorInset = UIEdgeInsetsMake(0, ScreenWidth, 0, 0);
          cell.cellData = self.aboutExpert;

          return cell;
        }

      } else if (indexPath.section == 2) { //评论

        if (indexPath.row == CommentCountLimit + 1) { //查看更多
          ExpertDetailBtnCell *cell = (ExpertDetailBtnCell *) [tableView dequeueReusableCellWithIdentifier:@"ExpertDetailBtnCell"];
          if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ExpertDetailBtnCell" owner:nil options:nil] lastObject];
          }
          cell.selectionStyle = UITableViewCellSelectionStyleNone;
          cell.expertId = self.expertId;
          cell.btnType = ExpertDetailBtnType_Comment;

          return cell;
        } else {
          CommentCell *cell = (CommentCell *) [tableView dequeueReusableCellWithIdentifier:@"CommentCell"];
          if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"CommentCell" owner:nil options:nil] lastObject];
          }
          cell.selectionStyle = UITableViewCellSelectionStyleNone;
          cell.cellData = [self.expertDetail.pro_topic_comments objectAtIndex:indexPath.row - 1];

          return cell;
        }

      } else { //约见保障计划
        ExpertDetailTextCell *cell = (ExpertDetailTextCell *) [tableView dequeueReusableCellWithIdentifier:@"ExpertDetailTextCell"];
        if (!cell) {
          cell = [[[NSBundle mainBundle] loadNibNamed:@"ExpertDetailTextCell" owner:nil options:nil] lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.cellData = TextProtectPlan;

        return cell;
      }
    }
  } else { //预约话题列表
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];

    //主标题
    cell.textLabel.font = GFontWithSize(GLargeFontSize);
    if (indexPath.row == self.selectIndex) {
      cell.textLabel.textColor = GOrangeColor;
    } else {
      cell.textLabel.textColor = GBlackColor;
    }

    TopicModel *topicModel = [self.expertDetail.pro_topic objectAtIndex:indexPath.row];
    cell.textLabel.text = topicModel.data.topic_name;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.contentView.transform = CGAffineTransformMakeScale(1, -1); //翻转

    return cell;
  }
}

#pragma mark TableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:YES]; //返回后选中状态消失

  if (tableView == self.tableView) {
    if (indexPath.section == 0 && indexPath.row != 0) { //专家话题
      [OperationManager gotoThemeDetailVcWithModel:self.expertDetail topicModel:[self.expertDetail.pro_topic objectAtIndex:indexPath.row - 1]];
    }
  } else { //预约话题列表
    //TODO: 预约按钮执行预约操作而非弹框了-暂不管
    //选中话题变色
    self.selectIndex = indexPath.row;
    [self.themeTableView reloadData];
    //收藏按钮变文字
    [self changeCollectBtnToText:indexPath.row];
  }
}

#pragma mark UIGestureRecognizerDelegate table添加手势（去掉对cell的影响）
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
  if ([touch.view isKindOfClass:[UITableView class]]) {
    return YES;
  }
  return NO;
}

#pragma mark ExpertDetailBtnDelegate 查看更多
- (void)goToMore {
  //重载table时的判断字段
  self.isShowMore = YES;
  //重载table
  [self.tableView reloadData];
}

#pragma mark - 私有方法
#pragma mark 分享（导航栏右按钮）
- (void)rightAction {
  //显示分享面板
  [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
    
      //设置分享内容 分享文案：话题名/推荐专家名  +  话题内容/专家介绍  + 头像（图片）
      if (self.expertDetail.pro_user_info.count > 0) {
        UserModel *userModel = self.expertDetail.pro_user_info[0];
        UserData *user = [userModel user_data];
        NSString *url = [NSString stringWithFormat:@"http://%@/portal/index/index/%ld",H5_API_HOST,(long)userModel.uid];
        [OperationManager shareWebPageToPlatformType:platformType title:user.user_name desc:self.aboutExpert imageUrl:user.user_profile_pic webUrl:url];
     }
    
  }];
}

#pragma mark 装配头图数据
- (void)loadHeadView {
  if (self.expertDetail.pro_user_info.count > 0) {
    UserData *user = [self.expertDetail.pro_user_info[0] user_data];
    [self.headImage sd_setImageWithURL:[NSURL URLWithString:user.user_profile_bg_pic] placeholderImage:[UIImage imageNamed:@"large_image_default"]];
    self.nameLabel.text = user.user_name;
    self.jobLabel.text = user.user_pro_title;
    self.locLabel.text = user.user_location_desc;
    self.seenLabel.text = [NSString stringWithFormat:@"%ld人见过", (long) user.pro_user_consulting_count];
    self.missLabel.text = [NSString stringWithFormat:@"%ld人想约", (long) user.like_count];
    self.collectBtn.selected = user.is_liked;
  }
}

#pragma mark 装载预约话题table
- (void)loadThemeTableView {
  [self.themeTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
  self.themeTableView.transform = CGAffineTransformMakeScale(1, -1); //翻转
  //footerView
  UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, NavHeight)];
  UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
  label.center = CGPointMake(ScreenWidth / 2, NavHeight / 2);
  label.textColor = GGrayWordColor1;
  label.font = GFontWithSize(GMiddleFontSize);
  label.text = @"请选择";
  UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(GNormalMargin, NavHeight - 1, ScreenWidth - GNormalMargin * 2, 1)];
  imageView.image = [UIImage imageNamed:@"ic_line"];
  [footerView addSubview:label];
  [footerView addSubview:imageView];
  footerView.transform = CGAffineTransformMakeScale(1, -1); //翻转
  footerView.backgroundColor = [UIColor whiteColor];
  self.themeTableView.tableFooterView = footerView;
  //添加手势-点击消失
  UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideThemeTable)];
  tap.delegate = self;
  [self.themeTableView addGestureRecognizer:tap];
}

#pragma mark 隐藏预约话题列表
- (void)hideThemeTable {
  self.themeTableView.hidden = YES;
  self.orderView.hidden = YES;
  //收藏按钮还原
  [self changeCollectBtnToImage];
}

#pragma mark 收藏按钮文本状态
- (void)changeCollectBtnToText:(NSInteger)index {
  TopicModel *topicModel = [self.expertDetail.pro_topic objectAtIndex:index];
  NSString *price = [NSString stringWithFormat:@"¥%.2f", topicModel.data.topic_price];
  [self.collectBtn setTitle:price forState:UIControlStateNormal];
  self.collectBtn.userInteractionEnabled = NO;
  [self.collectBtn setImage:nil forState:UIControlStateNormal];
  [self.collectBtn setImage:nil forState:UIControlStateSelected];
}

#pragma mark 收藏按钮图片状态
- (void)changeCollectBtnToImage {
  [self.collectBtn setTitle:nil forState:UIControlStateNormal];
  self.collectBtn.userInteractionEnabled = YES;
  [self.collectBtn setImage:[UIImage imageNamed:@"expert_no_collect_ic"] forState:UIControlStateNormal];
  [self.collectBtn setImage:[UIImage imageNamed:@"expert_collect_ic"] forState:UIControlStateSelected];
}

#pragma mark 获取关于专家文本的本来高度
- (CGFloat)getAboutExpertTextHeight {
  CGSize maxSize = CGSizeMake(ScreenWidth - GNormalMargin * 2, MAXFLOAT);
  NSDictionary *attrs = @{NSFontAttributeName : GCustomNormalFont};
  CGFloat height = [[CommonMethod sharedCommonMethod] heightForString:self.aboutExpert maxSize:maxSize attrs:attrs];
  height = height + GNormalMargin * 2;
  return height;
}

#pragma mark 收藏接口操作提取
-(void)operateCollect:(BOOL)isSucceed{
  if (isSucceed) {
    self.collectBtn.selected = !self.collectBtn.isSelected;
  } else {
    NSError *error = [UserModel getLastError];
    [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
  }
  [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}

@end
